package actions;

import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import utils.MessageViewer;
import utils.ParameterValidator;

import client.ClientSocketConnection;
import client_gui.ClientWindow;

public class ChangeEmailAction extends RLMAbstractAction {

	public ChangeEmailAction(ClientWindow owner) {
		setActionOwner(owner);
//		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));
		putValue(SMALL_ICON, loadIcon("images/email.png"));
		putValue(NAME, "Change Email");
		putValue(SHORT_DESCRIPTION, "Promena Email-a");
	}
	
	
	public void actionPerformed(ActionEvent e) {
		
		ClientWindow owner = getActionOwner();
		
		JPanel panel = new JPanel();
		JLabel label = new JLabel("Email:");
	    JTextField nicknameField = new JTextField();
	    nicknameField.setPreferredSize(new Dimension(150,20));
	    
	    panel.add(label);
	    panel.add(nicknameField);
	    
	    int action = JOptionPane.showConfirmDialog(owner, panel, "Enter Email", JOptionPane.OK_CANCEL_OPTION);
		
	    if (action != JOptionPane.OK_OPTION) {
	    	return;
	    }
	    
	    String newEmail = nicknameField.getText();
	    
		ParameterValidator.setRegex(ParameterValidator.mailRegExp);
		boolean flag = ParameterValidator.matchStrings(newEmail, 30);
		
		if (flag == false) {
			MessageViewer.showError(owner, "Bad e-mail parameter");
			return;
		}
	    
		ClientSocketConnection connection = owner.getApplicaton().retrieveSocketConnection();
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("CHMAIL ");
		buffer.append(owner.getApplicaton().getClientUser().getUsername());
		buffer.append(" ");
		buffer.append(newEmail);
		
		String completedMailInfo = buffer.toString();
		
		connection.setMessage(CHMAIL_CMD, completedMailInfo);
		
		String response;
		
		response = connection.buffers[CHMAIL_CMD].read();
		
		if ( response.startsWith("100") ) {
			
			owner.getApplicaton().getClientUser().setEmail(newEmail);
		}
	}
	
}
